<?php
/**
 * Created by PhpStorm.
 * User: geolo
 * Date: 2018/11/22
 * Time: 14:39
 */
namespace app\modules\api\models;
use app\models\VipOrder;
use app\models\Order;
use app\modules\api\models\OrderSubmitForm;

/**
 * @property  VipOrder Model
 */
class VipOrderSubmitForm extends Model
{
    public $order_id;
    public $is_pay;
    public $user_id;
    public $order_no;
    public $pay_price;
    private $wechat;
    private $order;
    public function rules()
    {
        return [
            [['store_id', 'user_id', 'order_no'], 'required'],
            [['store_id', 'user_id', 'is_pay' ], 'integer'],
            [[ 'pay_price'], 'number'],
            [['create_time'], 'string'],
            [['order_no'], 'string', 'max' => 255],
        ];
    }
    public function attributes()
    {
        return [
            'id' => 'ID',
            'store_id' => 'Store ID',
            'user_id' => '用户id',
            'order_no' => '订单号',
            'pay_price' => '实际支付费用',
            'is_pay' => '支付状态：0=未支付，1=已支付',
            'create_time' => '支付时间',
        ];
    }
    public function save(){
        $model = new VipOrder();
       $model->is_pay  = 0;
       $ordersubmit = new OrderSubmitForm();
       $model->order_no = $ordersubmit->getOrderNo();
       if($model->save()){
           return[
               'code'=>0,
               'msg'=>'保存成功',
               'id'=>$model->id,
           ];
       }
    }

    public function search(){
        $this->wechat = $this->getWechat();
        if (!$this->validate())
            return $this->getModelError();
        $this->order = VipOrder::findOne([
            'store_id' => $this->store_id,
            'id' => $this->order_id,
        ]);
        if (!$this->order)
            return [
                'code' => 1,
                'msg' => '订单不存在',
            ];
        if ($this->pay_type == 'WECHAT_PAY') {
            $res = $this->unifiedOrder('viporder');
            if (isset($res['code']) && $res['code'] == 1) {
                return $res;
            }

            //记录prepay_id发送模板消息用到
            FormId::addFormId([
                'store_id' => $this->store_id,
                'user_id' => $this->user->id,
                'wechat_open_id' => $this->user->wechat_open_id,
                'form_id' => $res['prepay_id'],
                'type' => 'prepay_id',
                'order_no' => $this->order->order_no,
            ]);

            $pay_data = [
                'appId' => $this->wechat->appId,
                'timeStamp' => '' . time(),
                'nonceStr' => md5(uniqid()),
                'package' => 'prepay_id=' . $res['prepay_id'],
                'signType' => 'MD5',
            ];
            $pay_data['paySign'] = $this->wechat->pay->makeSign($pay_data);
            return [
                'code' => 0,
                'msg' => 'success',
                'data' => (object)$pay_data,
                'res' => $res,
                'body' => 'viporder',
            ];
        }
    }
    private function unifiedOrder($goods_names)
    {
        $res = $this->wechat->pay->unifiedOrder([
            'body' => $goods_names,
            'out_trade_no' => $this->order->order_no,
            'total_fee' => $this->order->pay_price * 100,
            'notify_url' => \Yii::$app->request->hostInfo . \Yii::$app->request->baseUrl . '/vip-pay-notify.php',
            'trade_type' => 'JSAPI',
            'openid' => $this->user->wechat_open_id,
        ]);
        $notify_url=\Yii::$app->request->hostInfo . \Yii::$app->request->baseUrl . '/vip-pay-notify.php';
        \Yii::$app->log->targets[0]->logFile = \Yii::getAlias('@runtime').DIRECTORY_SEPARATOR.'logs'.DIRECTORY_SEPARATOR.'app2.log';
        \Yii::warning($notify_url);
        if (!$res)
            return [
                'code' => 1,
                'msg' => '支付失败',
            ];
        if ($res['return_code'] != 'SUCCESS') {
            return [
                'code' => 1,
                'msg' => '支付失败，' . (isset($res['return_msg']) ? $res['return_msg'] : ''),
                'res' => $res,
            ];
        }
        if ($res['result_code'] != 'SUCCESS') {
            if ($res['err_code'] == 'INVALID_REQUEST') {//商户订单号重复
                $this->order->order_no = (new OrderSubmitForm())->getOrderNo();
                $this->order->save();
                return $this->unifiedOrder($goods_names);
            } else {
                return [
                    'code' => 1,
                    'msg' => '支付失败，' . (isset($res['err_code_des']) ? $res['err_code_des'] : ''),
                    'res' => $res,
                ];
            }
        }
        return $res;
    }


}